/**
 * @class Bible.form.SearchFieldLocal
 * @extends Ext.form.TwinTriggerField
 * <pre><code>var searchFieldLocal = new Bible.form.SearchFieldLocal({
    store: ds,
    onKeyup: true,
    emptyText: '...',
    filterByFields: ['name', 'title', {name:'modifiedDate', type:'date', dateFormat: strDateTimeFormat}]
});</code></pre>
 * @author Matei Nicolae
 */
Bible.form.SearchFieldLocal = Ext.extend(Ext.form.TwinTriggerField,{
    /**
     * @cfg {Array}
     */
    filterByFields: [],
    /**
     * @cfg {Ext.form.Checkbox} checkFilter
     */
    validationEvent:false,
    validateOnBlur:false,
    trigger1Class:'x-form-clear-trigger',
    trigger2Class:'x-form-search-trigger',
    trigger1Qtip: false,
    trigger2Qtip: false,
    hideTrigger1:true,
    hideTrigger2:false,
    hasSearch : false,
    width: 150,
	emptyText: '',
	onKeyup: true,
	filterCombos: false, // New property
    minChars: 2,

    initComponent : function(){
        var me = this;
        Bible.form.SearchFieldLocal.superclass.initComponent.call(me);
        if(me.trigger1Qtip){
            me.triggerConfig.cn[0]['ext:qtip'] = me.trigger1Qtip;
        }
        if(me.trigger2Qtip){
            me.triggerConfig.cn[1]['ext:qtip'] = me.trigger2Qtip;
        }
		me.highlightsTerms = [];
    },

    initEvents : function(){
        var me = this;
		Bible.form.SearchFieldLocal.superclass.initEvents.call(me);
		me.on({
            scope: me,
            specialkey: function(f, e){
                if(e.getKey() == e.ENTER){
                    this.onTrigger2Click();
                }
            }
        });
        if(me.onKeyup) {
            me.el.on('keyup', me.onTrigger2Click, me);
        }

        if(me.checkFilter){
            //this.mon(this.checkFilter, 'check', function(){
            me.mon(me.checkFilter, 'toggle', function(){
				me.onTrigger2Click();
            }, me);

            me.mon(me.store, 'load', function(){
                if(me.checkFilter.pressed){
                    me.onTrigger2Click();
                }
            }, me);
        }
    },

    setValue : function(v){
		Bible.form.SearchFieldLocal.superclass.setValue.apply(this, arguments);
        if(v.length < this.minChars){
            this.onTrigger1Click();
        } else {
            this.onTrigger2Click();
        }
    },

    /**
     * The function that should handle the trigger's click event.  This method does nothing by default
     * until overridden by an implementing function. See {@link Ext.form.TriggerField#onTriggerClick}
     * for additional information.
     * @method
     * @param {EventObject} e
     */
    onTrigger1Click : function(){
        var me = this,
            combos,
            j = 0;
		me.highlightsTerms = [];
        if(me.hasSearch){
			me.el.dom.value = '';
            me.triggers[0].hide();
            me.hasSearch = false;
            me.store.filterBy(function(n) {return true;});
//            this.store.clearFilter(false);
			// verify if there are combos that have to filter store
	        if(me.filterCombos){
	        	combos = me.filterCombos;
	            for(; j<combos.length; j++) {
	            	if(combos[j].combo.getValue())
	            		me.store.filter(combos[j].field, combos[j].combo.getValue());
	            }
	        }
			me.focus();
        }
    },

    /**
     * The function that should handle the trigger's click event.  This method does nothing by default
     * until overridden by an implementing function. See {@link Ext.form.TriggerField#onTriggerClick}
     * for additional information.
     * @method
     * @param {EventObject} e
     */
    onTrigger2Click : function(){
        var me = this,
            text = me.getRawValue(),
            notFilter,
            re,
            fields,
            combos,
            w = 0;
		me.highlightsTerms = [];
        if(text.length < me.minChars){
            me.onTrigger1Click();
            return;
        }
        me.hasSearch = true;
        me.triggers[0].show();
		me.focus();
		
		var highlights = Ext.util.Terminology.createHighlightsTerms(text, me.minChars, true);
		re = highlights.segments;
		me.highlightsTerms = highlights.terms;

		fields = me.filterByFields;
        combos = me.filterCombos;
		
		//notFilter = (fields.length == 0) || (this.checkFilter ? !this.checkFilter.getValue() : false);
        notFilter = (fields.length == 0) || (me.checkFilter ? !me.checkFilter.pressed : false);
		
		for(; w<re.length; w++) {
			//re[w] = new RegExp(Ext.escapeRe(re[w]), 'i'); // Any match
			re[w] = new RegExp(Bible.escapeDiacriticsRe(Ext.escapeRe(re[w])), 'i'); // Any match
		}
		
		me.store.isBeforeFilter = true;
		me.store.filterBy(function(r){
			if(notFilter){
                return true;
            }
            var rez,
                i = 0,
                j;
			for(; i<re.length; i++) { // for each word in Filter
                rez = false;
				for(j=0; j<fields.length; j++) { // for each field
					if(typeof fields[j] != 'object') {
						if(re[i].test(r.get( fields[j] ))) {
							rez = true;
							j = fields.length;
						}
					} else {
						if(re[i].test(r.get( fields[j].name ))) {
							rez = true;
							j = fields.length;
						} else if(fields[j].type == 'date') {
							var dFormat = fields[j].dateFormat;
							if(typeof dFormat == 'undefined') dFormat = 'd/m/Y';
							var val = new Date(r.get( fields[j].name )).format(dFormat);
							if(re[i].test(val)) {
								rez = true;
								j = fields.length;
							}
						}
					}
				}
				if(!rez) { // if can't find a word in all Fields
					return false;
				}
			}
			if(combos){
	            for(j=0; j<combos.length; j++) {
	            	if(combos[j].combo.getValue()){
		            	if(combos[j].combo.getValue() != r.get( combos[j].field )) {
							 return false;
						}
	            	}
	            }
	        }
			return true;
		});
		me.store.isBeforeFilter = false;
    }
});

Ext.reg('searchfieldlocal', Bible.form.SearchFieldLocal);




/**
 * @class Bible.form.ComboSearchFieldLocal
 * @extends Ext.form.ComboBox
 * <pre><code>var comboSearchFieldLocal = new Bible.form.ComboSearchFieldLocal({
    store: ds,
    emptyText: AppKeyWords.find,
});</code></pre>
 * @author Matei Nicolae
 */
Bible.form.ComboSearchFieldLocal = Ext.extend(Ext.form.ComboBox,{
    validationEvent:false,
    validateOnBlur:false,
    trigger1Class:'x-form-clear-trigger',
    hideTrigger1:true,
    hideTrigger2:false,
    hasSearch : false,
    emptyText: '',

    initComponent : function(){
		Bible.form.ComboSearchFieldLocal.superclass.initComponent.call(this);
        this.triggerConfig = {
            tag:'span', cls:'x-form-twin-triggers', cn:[
            {tag: "img", src: Ext.BLANK_IMAGE_URL, alt: "", cls: "x-form-trigger " + this.trigger1Class},
            {tag: "img", src: Ext.BLANK_IMAGE_URL, alt: "", cls: "x-form-trigger " + this.trigger2Class}
        ]};

        this.addEvents(
            /**
             * @event clearfilter
             * Fires when the clear trigger is clicked : onTrigger1Click
             * @param {Whitney.form.ComboSearchFieldLocal} this This combo field
             */
            'clearfilter'
        );
    },
    
    initEvents : function(){
		Bible.form.ComboSearchFieldLocal.superclass.initEvents.call(this);

        this.triggers[0].hide();
        
        this.on({
            scope: this,
            select: function(){
                //console.debug('ComboSearchFieldLocal select');
                this.onFilter();
            },
            change: function(combo, newValue, oldValue){
                if(newValue == ''){
                    console.debug('change to blank -> clearSearch');
                    this.clearSearch();
                }
            }
        });

    },

    initTrigger : Ext.form.TwinTriggerField.prototype.initTrigger,

    getTriggerWidth: Ext.form.TwinTriggerField.prototype.getTriggerWidth,

    onDestroy: Ext.form.TwinTriggerField.prototype.onDestroy,

    /**
     * The function that should handle the trigger's click event.  This method does nothing by default
     * until overridden by an implementing function. See {@link Ext.form.TriggerField#onTriggerClick}
     * for additional information.
     * @method
     * @param {EventObject} e
     */
    onTrigger1Click : function(){
        //console.debug('onTrigger1Click');
        this.clearSearch();
    },

    /**
     * The function that should handle the trigger's click event.  This method does nothing by default
     * until overridden by an implementing function. See {@link Ext.form.TriggerField#onTriggerClick}
     * for additional information.
     * @method
     * @param {EventObject} e
     */
    onTrigger2Click : function(){
        //console.debug('onTrigger2Click');
        this.onTriggerClick();
    },

    /**
     * 
     */
    clearSearch: function(){
        var me = this;
        //console.debug('clearSearch');
        if(me.hasSearch){
            me.triggers[0].hide();
            me.hasSearch = false;
            me.store.clearFilter(false);
            me.reset();
//            this.postBlur();
            me.onBlur();
            me.fireEvent('clearfilter', me);
			//this.el.focus();
        }
    },

    onFilter: function(){
        this.hasSearch = true;
        this.triggers[0].show();
    }
});

Ext.reg('combosearchfieldlocal', Bible.form.ComboSearchFieldLocal);